<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php
class TripsController extends AppController {

	var $name = 'Trips';
	var $uses = array('Trip', 'TripInfo', 'MediaInfo', 'NodeInfo', 'PointOfInterestInfo',  'VehicleNodeList', 'VehiclePoiList', 'RouteSchedule', 'RoutePoiAssoc');

	function index() {
		
		list($order, $limit, $page) = $this->setupPagination();
		$this->set('trips', $this->Trip->findAll(NULL, NULL, $order, $limit, $page));
		
	}

	function view($id = null) {
		
		$this->checkRecordExistance($id);
		$this->set('trip', $this->Trip->read(null, $id));
		
	}

	function add() {
		
		if (empty($this->data)) {
			if (!is_array($vehicles = $this->Trip->Vehicle->generateList(NULL, 'vehicle_license_no ASC'))) {
				$vehicles = array();
			}
			if (!is_array($routeSchedules = $this->Trip->RouteSchedule->generateList(array('route_schedule_status'=>1), 'route_schedule_code ASC'))) {
				$routeSchedules = array();
			}
			foreach ($vehicles as $vehicleId => $vehicleLicenseNo) {
				$vehicleCode = $this->Trip->Vehicle->field('Vehicle.vehicle_code', "Vehicle.id =".$vehicleId);
				$vehicles[$vehicleId] = $vehicleLicenseNo.' ('.$vehicleCode.')';
			}
			foreach ($routeSchedules as $routeScheduleId => $routeScheduleCode) {
				$routeScheduleName = $this->Trip->RouteSchedule->field('RouteSchedule.route_schedule_name', "RouteSchedule.id =".$routeScheduleId);
				$routeSchedules[$routeScheduleId] = $routeScheduleCode.' ('.$routeScheduleName.')';
			}
			$this->set('vehicles', $vehicles);
			$this->set('routeSchedules', $routeSchedules);
			$this->render();
			
		} else {
			
			$this->cleanupData();
			$this->setTripStatusTime();
			
			$this->Trip->begin();
			$this->TripInfo->begin();
			$this->MediaInfo->begin();
			$this->NodeInfo->begin();
			$this->PointOfInterestInfo->begin();
			$this->VehiclePoiList->begin();
			$this->VehicleNodeList->begin();
			
			$allowCommit = true;
			
			$fields['Trip.vehicle_id']        = $this->data['Trip']['vehicle_id']; 
			$fields['Trip.route_schedule_id'] = $this->data['Trip']['route_schedule_id'];
			if ($this->Trip->hasAny($fields)) {
				// Trip with the same vehicle- route schedule combination already exists
				$allowCommit = false;
				$this->Session->setFlash('A Trip with this Vehicle-Route schedule combination already exists.', 'message_error');
			}
			
			
			if ($allowCommit) {
				if ($this->Trip->save($this->data)) {
					$tripId = $this->Trip->getLastInsertID();
					if ($this->data['Trip']['route_schedule_id'] != NULL) {
						if (!$this->pushToTripInfoQueue($tripId)) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating media info queue.', 'message_error');
						}
						if (!$this->pushToMediaInfoQueue($this->data['Trip']['route_schedule_id'])) {
							$allowCommit = true;
							$this->Session->setFlash('Error while updating Media infos queue, Unable to delete trip.', 'message_error');
						}
						if (!$this->pushToVehicleNodeList($this->data['Trip']['vehicle_id'], $this->data['Trip']['route_schedule_id'])) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating vehicle-node list.', 'message_error');
						}
						if (!$this->pushToVehiclePoiList($this->data['Trip']['vehicle_id'], $this->data['Trip']['route_schedule_id'])) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating vehicle-poi list.', 'message_error');
						}
						if (!$this->pushToNodeInfoQueue('vehicle', $this->data['Trip']['vehicle_id'])) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating node info queue.', 'message_error');
						}
						if (!$this->pushToPoiInfoQueue('vehicle', $this->data['Trip']['vehicle_id'])) {
							$allowCommit = false;
							$this->Session->setFlash('Error while updating poi info queue.', 'message_error');
						}
					}
				} else {
					$allowCommit = false;
					$this->Session->setFlash('Please correct errors below.', 'message_error');
				}
			}
			if ($allowCommit) {
				$this->Trip->commit();
				$this->TripInfo->commit();
				$this->MediaInfo->commit();
				$this->NodeInfo->commit();
				$this->PointOfInterestInfo->commit();
				$this->VehiclePoiList->commit();
				$this->VehicleNodeList->commit();
				$this->Session->setFlash('New Trip has been added.', 'message_ok');
				$this->redirect('/trips/index');
			} else {
				$this->Trip->rollback();
				$this->TripInfo->rollback();
				$this->MediaInfo->rollback();
				$this->NodeInfo->rollback();
				$this->PointOfInterestInfo->rollback();
				$this->VehiclePoiList->rollback();
				$this->VehicleNodeList->rollback();
				if (!is_array($vehicles = $this->Trip->Vehicle->generateList(NULL, 'vehicle_license_no ASC'))) {
					$vehicles = array();
				}
				if (!is_array($routeSchedules = $this->Trip->RouteSchedule->generateList(array('route_schedule_status'=>1), 'route_schedule_code ASC'))) {
					$routeSchedules = array();
				}
				foreach ($vehicles as $vehicleId => $vehicleLicenseNo) {
					$vehicleCode = $this->Trip->Vehicle->field('Vehicle.vehicle_code', "Vehicle.id =".$vehicleId);
					$vehicles[$vehicleId] = $vehicleLicenseNo.' ('.$vehicleCode.')';
				}
				foreach ($routeSchedules as $routeScheduleId => $routeScheduleCode) {
					$routeScheduleName = $this->Trip->RouteSchedule->field('RouteSchedule.route_schedule_name', "RouteSchedule.id =".$routeScheduleId);
					$routeSchedules[$routeScheduleId] = $routeScheduleCode.' ('.$routeScheduleName.')';
				}
				$this->set('vehicles', $vehicles);
				$this->set('routeSchedules', $routeSchedules);
			}
			
		}
		
	}

	function edit($id = null) {
		
		if (empty($this->data)) {
			
			$this->checkRecordExistance($id);
			$this->data = $this->Trip->read(null, $id);
			if ($this->data['Trip']['route_schedule_id'] == NULL) {
				$this->data['Trip']['route_schedule_id'] = 0;
			}
			$vehicleCode       = $this->Trip->Vehicle->field('vehicle_code', "Vehicle.id =".$this->data['Trip']['vehicle_id']);
			$routeScheduleCode = $this->Trip->RouteSchedule->field('route_schedule_code', "RouteSchedule.id =".$this->data['Trip']['route_schedule_id']);
			if ($routeScheduleCode == null) {
				$routeScheduleCode = "None";
			}
			$this->set('vehicleCode', $vehicleCode);
			$this->set('routeScheduleCode', $routeScheduleCode);
			$this->setTripStatuses($id);
			
		} else {
			
			// To prevent read only field modification by any malpractice
			$this->data['Trip']['vehicle_id']       = $this->Trip->field('vehicle_id', "Trip.id =".$id);
			$this->data['Trip']['route_schedule_id'] = $this->Trip->field('route_schedule_id', "Trip.id =".$id);
			$this->cleanupData();
			
			if ($this->data['Trip']['route_schedule_id'] == NULL) {
				$this->data['Trip']['route_schedule_id'] = 0;
			} 
			// Remove below lines
			// $this->pushToVehicleNodeList($this->data['Trip']['vehicle_id'], $this->data['Trip']['route_schedule_id']);
			// $this->popFromVehicleNodeList($this->data['Trip']['vehicle_id'], $this->data['Trip']['route_schedule_id']);
			 //exit(0);
			
			 
			$activeTripExists = $this->data['Trip']['trip_status'] == "S" && 
			$this->Trip->findCount(array('Trip.trip_status'=>"S", 'Trip.vehicle_id'=>$this->data['Trip']['vehicle_id'], 'Trip.id'=>'<> '.$id ))>0; 
			if ($activeTripExists) {
				$this->Session->setFlash('An Active trip already exists for this vehicle. It must either be cancelled or ended before changing this trip status to started.', 'message_error');
				$vehicleCode       = $this->Trip->Vehicle->field('vehicle_code', "Vehicle.id =".$this->data['Trip']['vehicle_id']);
				$routeScheduleCode = $this->Trip->RouteSchedule->field('route_schedule_code', "RouteSchedule.id =".$this->data['Trip']['route_schedule_id']);
				if($routeScheduleCode == NULL){
					$routeScheduleCode = "None";
				}
				$this->set('vehicleCode', $vehicleCode);
				$this->set('routeScheduleCode', $routeScheduleCode);
				$this->setTripStatuses($id);
				return 0;
			}
			if ($this->Trip->field('trip_status', array('Trip.id'=>$id)) === $this->data['Trip']['trip_status']) {
				$updatePushRequired = false;
			} else {
				$updatePushRequired = true;
				$this->setTripStatusTime();
			}
			$this->Trip->begin();
			if($this->data['Trip']['route_schedule_id'] == 0){
				$this->data['Trip']['route_schedule_id'] = NULL; //  To keep foreign key constraints
			}
			if($this->Trip->save($this->data)) {
				if($updatePushRequired){
					//$this->pushToTripUpdateQueue($id);		//whenever the status changes
				}
				$this->Trip->commit();
				$this->Session->setFlash('The Trip has been saved.', 'message_ok');
				$this->redirect('/trips/index');
			} else {
				$this->Trip->rollback();
				$this->Session->setFlash('Please correct errors below.', 'message_error');
				$vehicleCode       = $this->Trip->Vehicle->field('vehicle_code', "Vehicle.id =".$this->data['Trip']['vehicle_id']);
				$routeScheduleCode = $this->Trip->RouteSchedule->field('route_schedule_code', "RouteSchedule.id =".$this->data['Trip']['route_schedule_id']);
				if($routeScheduleCode == null){
					$routeScheduleCode = "None";
				}
				$this->set('vehicleCode', $vehicleCode);
				$this->set('routeScheduleCode', $routeScheduleCode);
				$this->setTripStatuses($id);
			}
			
		}
		
	}

	function delete($id = null) {
		
		$this->checkRecordExistance($id);
		if(low($this->Trip->field('trip_status', "Trip.id=".$id)) == "s"){
			$this->Session->setFlash("The Trip status is 'Started'; It cannot be deleted until status changes to 'Cancelled' or 'Ended'.", 'message_error');
			$this->redirect('/trips/index');
			exit(0);
		}
		$this->Trip->begin();
		$this->TripInfo->begin();
		$this->VehicleNodeList->begin();
		$this->VehiclePoiList->begin();
		$this->MediaInfo->begin();
		$this->NodeInfo->begin();
		$this->PointOfInterestInfo->begin();
		$allowCommit = true;
		$trip = $this->Trip->find(array('Trip.id'=>$id));
		$this->data['Trip']['vehicle_id']        = $trip['Trip']['vehicle_id'];
		$this->data['Trip']['route_schedule_id'] = $trip['Trip']['route_schedule_id'];
	
		if (!$this->refreshTripInfoQueue($id)) {
			$allowCommit = true;
			$this->Session->setFlash('Error while updating Route schedule infos queue, Unable to delete trip.', 'message_error');
		}
		/*
		if (!$this->refreshMediaInfoQueue($trip['Trip']['route_schedule_id'])) {
			$allowCommit = true;
			$this->Session->setFlash('Error while updating Media infos queue, Unable to delete trip.', 'message_error');
		}
		*/
		if (!$this->refreshNodeInfoQueue('vehicle', $trip['Trip']['vehicle_id'])) {
			$allowCommit = true;
			$this->Session->setFlash('Error while updating Node infos queue, Unable to delete trip.', 'message_error');
		}
		if (!$this->refreshPoiInfoQueue('vehicle', $trip['Trip']['vehicle_id'])) {
			$allowCommit = true;
			$this->Session->setFlash('Error while updating PoI infos queue, Unable to delete trip.', 'message_error');
		}
		if (!$this->popFromVehicleNodeList($trip['Trip']['vehicle_id'], $trip['Trip']['route_schedule_id'])) {
			$allowCommit = true;
			$this->Session->setFlash('Error while updating vehicle-node list, Unable to delete trip.', 'message_error');
		}
		if (!$this->popFromVehiclePoiList($trip['Trip']['vehicle_id'], $trip['Trip']['route_schedule_id'])) {
			$allowCommit = true;
			$this->Session->setFlash('Error while updating vehicle-poi list, Unable to delete trip.', 'message_error');
		}
		
		if ($this->Trip->del($id)) {			
			if ($allowCommit) {
				$this->Trip->commit();
				$this->TripInfo->commit();
				$this->VehicleNodeList->commit();
				$this->VehiclePoiList->commit();
				$this->MediaInfo->commit();
				$this->NodeInfo->commit();
				$this->PointOfInterestInfo->commit();
				$this->Session->setFlash('The Trip deleted.', 'message_ok');
				$this->redirect('/trips/index');
			} else {
				$this->Trip->rollback();
				$this->TripInfo->rollback();
				$this->VehicleNodeList->rollback();
				$this->VehiclePoiList->rollback();
				$this->MediaInfo->rollback();
				$this->NodeInfo->rollback();
				$this->PointOfInterestInfo->rollback();
				$this->redirect('/trips/index');
			}
		} else {
			$this->Trip->rollback();
			$this->TripInfo->rollback();
			$this->VehicleNodeList->rollback();
			$this->VehiclePoiList->rollback();
			$this->MediaInfo->rollback();
			$this->NodeInfo->rollback();
			$this->showError(ERROR_DELETE, 'Unable to delete record.');
		}
		
	}
	
	function view_multiple($id = null) {
		$flag = true;
		if (isset($this->params['url']['ids'])) {
			$ids = explode(";", $this->params['url']['ids']);
			if (count($ids) > 0) {
				foreach ($ids as $id) {
					if ($id != null) {
						$id = intval($id); 
						unset($fields);
						$fields['Trip.id'] = $id;
						if ($this->Trip->hasAny($fields)) {
							$validIds[] = $id; 
						}
					} 
				}
				if (isset($validIds)) {
					$idList       = implode(",", $validIds);
					$conditions   = array("Trip.id IN ($idList)");
					$trips        = $this->Trip->findAll($conditions);
				} else {
					$flag = false;
				}
			} else {
				$flag = false;
			}
		} else {
			$flag = false;
		}
		if ($flag) {
			$this->set('trips', $trips);
		} else {
			$this->Session->setFlash('No Trips selected to view.', 'message_error');
			$this->redirect('/trips/index');
		}
	}
	
	
	function setTripStatuses($id) {
		
		if ($this->Trip->field('trip_status', array('Trip.id'=>$id))=="S") {
			$this->set('statuses', array("S"=>"Started", "C"=>"Cancelled"));
		} else if ($this->Trip->field('trip_status', array('Trip.id'=>$id))=="E") {
			$this->set('statuses', array("E"=>"Ended", "S"=>"Started"));
		} else if ($this->Trip->field('trip_status', array('Trip.id'=>$id))=="C") {
			$this->set('statuses', array("C"=>"Cancelled", "S"=>"Started"));
		} else if ($this->Trip->field('trip_status', array('Trip.id'=>$id))=="I"){
			$this->set('statuses', array("I"=>"Inactive", "S"=>"Started"));		
		}
		
	}
	
	function setTripStatusTime() {
		
		switch ($this->data['Trip']['trip_status']) {
			case "I":
			case "":
				break;
			case "S":
				$this->data['Trip']['trip_last_start_time']  = date('Y-m-d H:i:s', time());
				break;
			case "E":
				$this->data['Trip']['trip_last_end_time']    = date('Y-m-d H:i:s', time()); 
				break;
			case "C":
				$this->data['Trip']['trip_last_cancel_time'] = date('Y-m-d H:i:s', time());
				break;
		}
		
	}
	
	
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	function pushToTripInfoQueue($id) {
		
		$field['trip_info_reference'] = $id;
		if($this->TripInfo->hasAny($field)) {
			return true;
		} else {
			$data['TripInfo']['trip_info_reference'] = $id;
			$data['TripInfo']['vehicle_id'] = $this->data['Trip']['vehicle_id'];
			$data['TripInfo']['route_schedule_id'] = $this->data['Trip']['route_schedule_id'];;
			return $this->TripInfo->save($data);
		}
		
	}
	

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $routeScheduleId
	 * @return unknown
	 */
	function refreshTripInfoQueue($tripId) {
		
		$fields['TripInfo.trip_info_reference'] = $tripId;
		if ($this->TripInfo->hasAny($fields)) {
			// Already exists, then delete it		
			$tripInfoId = $this->TripInfo->field('TripInfo.id', $fields);
			return $this->TripInfo->del($tripInfoId);	
		} else {
			return $this->pushToTripInfoQueue($tripId);
		}
		
	}
	
	/**
	 * Pushes a new entry to the media info queue 
	 * Do nothing if an entry with same info type and reference already exists
	 */
	function pushToMediaInfoQueue($referenceId) {
		
		$fields['MediaInfo.media_info_type'] = "media_plan"; 
		$fields['MediaInfo.media_info_reference'] = $referenceId;
		if ($this->MediaInfo->hasAny($fields)) {
			// Entry already exists; Just return
			return true;
		}
		$data['MediaInfo']['media_info_type'] = 'media_plan';
		$data['MediaInfo']['media_info_reference'] = $referenceId;
		if ($this->MediaInfo->save($data)) {
			return true;
		} else {
			return false;
		}
		
	}
	
	/**
	 * If a reference id is present delete it.
	 * Else create a new reference
	 */
	function refreshMediaInfoQueue($id) {
		
		$fields['MediaInfo.media_info_type']      = "media_plan"; 
		$fields['MediaInfo.media_info_reference'] = $id;
		if ($this->MediaInfo->hasAny($fields)) {
			$mediaInfoId = $this->MediaInfo->field('MediaInfo.id', $fields);
			return $this->MediaInfo->del($mediaInfoId);
		} else {
			return $this->pushToMediaInfoQueue('media_plan', $id);
		}
		
	}
	
	/**
	 * Pushes a new entry to the node info queue 
	 * Do nothing if an entry with same info type and reference already exists
	 */
	function pushToNodeInfoQueue($infoType, $referenceId) {
		
		$fields['node_info_type'] = $infoType; 
		$fields['node_info_reference'] = $referenceId;
		if ($this->NodeInfo->hasAny($fields)) {
			// Entry already exists; Just return
			return true;
		}
		$data['NodeInfo']['id']                   = null;
		$data['NodeInfo']['node_info_type']      = $infoType;
		$data['NodeInfo']['node_info_reference'] = $referenceId;
		if ($this->NodeInfo->save($data)) {
			return true;
		} else {
			return false;
		}
		 
	}
	
	/**
	 * If a reference id is present delete it.
	 * Else create a new reference
	 *
	 * @param unknown_type $referenceId
	 * @return unknown
	 */
	function refreshNodeInfoQueue($infoType, $referenceId) {
		
		$fields['NodeInfo.node_info_reference'] = $referenceId;
		$fields['NodeInfo.node_info_type'] = $infoType;
		if ($this->NodeInfo->hasAny($fields)) {
			$nodeInfoId = $this->NodeInfo->field('NodeInfo.id', $fields);
			return $this->NodeInfo->del($nodeInfoId);
		} else {
			// Do nothing
			//return $this->pushToNodeInfoQueue($infoType, $referenceId);
		}
		
	}
	
	/**
	 * Pushes a new entry to the poi info queue 
	 * Do nothing if an entry with same info type and reference already exists
	 */
	function pushToPoiInfoQueue($infoType, $referenceId) {
		
		$fields['point_of_interest_info_type']      = $infoType; 
		$fields['point_of_interest_info_reference'] = $referenceId;
		if ($this->PointOfInterestInfo->hasAny($fields)) {
			// Entry already exists; Just return
			return true;
		}
		$data['PointOfInterestInfo']['id']                               = null;
		$data['PointOfInterestInfo']['point_of_interest_info_type']      = $infoType;
		$data['PointOfInterestInfo']['point_of_interest_info_reference'] = $referenceId;
		if ($this->PointOfInterestInfo->save($data)) {
			return true;
		} else {
			return false;
		}
		 
	}
	
	/**
	 * If a reference id is present delete it.
	 * Else create a new reference
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	function refreshPoiInfoQueue($infoType, $referenceId) {
		
		$fields['PointOfInterestInfo.point_of_interest_info_reference'] = $referenceId;
		$fields['PointOfInterestInfo.point_of_interest_info_type'] = $infoType;
		if ($this->PointOfInterestInfo->hasAny($fields)) {
			$poiInfoId = $this->PointOfInterestInfo->field('PointOfInterestInfo.id', $fields);
			return $this->PointOfInterestInfo->del($poiInfoId);
		} else {
			return $this->pushToPoiInfoQueue($infoType, $referenceId);
		}
		
	}
	
	function pushToVehicleNodeList($vehicleId, $routeScheduleId) {
		
		$flag = true;
		$routeSchedule =  $this->RouteSchedule->read(null, $routeScheduleId);
		foreach ($routeSchedule['RouteScheduleNodeAssoc'] as $rsna) {
			$fields['vehicle_id'] = $vehicleId;
			$fields['node_id'] =    $rsna['node_id'];
			unset($data);
			if ($this->VehicleNodeList->hasAny($fields)) {
				// Entry already exists; Just increment count.
				$data = $this->VehicleNodeList->find($fields);
				$data['VehicleNodeList']['vehicle_node_count']++;
			} else {
				// Create a new entry
				$data['VehicleNodeList']['id']         = null;
				$data['VehicleNodeList']['vehicle_id']         = $vehicleId;
				$data['VehicleNodeList']['node_id']            = $rsna['node_id'];
				$data['VehicleNodeList']['vehicle_node_count'] = 1;
			}
			if (!$this->VehicleNodeList->save($data)) {
				$flag = false;
				break;
			}
		}
		return $flag;
	}
	
	function popFromVehicleNodeList($vehicleId, $routeScheduleId) {
		
		$flag = true;
		$routeSchedule =  $this->RouteSchedule->read(null, $routeScheduleId);
		foreach ($routeSchedule['RouteScheduleNodeAssoc'] as $rsna) {
			$fields['vehicle_id'] = $vehicleId;
			$fields['node_id'] =    $rsna['node_id'];
			unset($data);
			if ($this->VehicleNodeList->hasAny($fields)) {
				// Entry exists; decrement cout an if count is zero delete th entry
				$data = $this->VehicleNodeList->find($fields);
				$data['VehicleNodeList']['vehicle_node_count']--;
				if ($data['VehicleNodeList']['vehicle_node_count'] <= 0) {
					// delete entry
					if (!$this->VehicleNodeList->del($data['VehicleNodeList']['id'])) {
						$flag = false;
						break;
					}
				} else {
					// update entry
					if (!$this->VehicleNodeList->save($data)) {
						$flag = false;
						break;
					}
				}
			} else {
				// Do nothing
			}
		}
		return $flag;
	}
	
	function pushToVehiclePoiList($vehicleId, $routeScheduleId) {
		
		$flag = true;
		$this->RouteSchedule->recursive=3;
		$routeSchedule =  $this->RouteSchedule->read(null, $routeScheduleId);
		foreach ($routeSchedule['Route']['RoutePoiAssoc'] as $rpa) {
			$fields['vehicle_id']           = $vehicleId;
			$fields['point_of_interest_id'] = $rpa['point_of_interest_id'];
			unset($data);
			if ($this->VehiclePoiList->hasAny($fields)) {
				// Entry already exists; Just increment count.
				$data = $this->VehiclePoiList->find($fields);
				$data['VehiclePoiList']['vehicle_poi_count']++;
			} else {
				// Create a new entry
				$data['VehiclePoiList']['id']                   = null;
				$data['VehiclePoiList']['vehicle_id']           = $vehicleId;
				$data['VehiclePoiList']['point_of_interest_id'] = $rpa['point_of_interest_id'];
				$data['VehiclePoiList']['vehicle_poi_count']   = 1;
			}
			if (!$this->VehiclePoiList->save($data)) {
				$flag = false;
				break;
			}
		}
		return $flag;
	}
	
	function popFromVehiclePoiList($vehicleId, $routeScheduleId) {
		
		$flag = true;
		$this->RouteSchedule->recursive=3;
		$routeSchedule =  $this->RouteSchedule->read(null, $routeScheduleId);
		foreach ($routeSchedule['Route']['RoutePoiAssoc'] as $rpa) {
			$fields['vehicle_id']           = $vehicleId;
			$fields['point_of_interest_id'] = $rpa['point_of_interest_id'];
			unset($data);
			if ($this->VehiclePoiList->hasAny($fields)) {
				// Entry exists; decrement cout an if count is zero delete th entry
				$data = $this->VehiclePoiList->find($fields);
				$data['VehiclePoiList']['vehicle_poi_count']--;
				if ($data['VehiclePoiList']['vehicle_poi_count'] <= 0) {
					// delete entry
					if (!$this->VehiclePoiList->del($data['VehiclePoiList']['id'])) {
						$flag = false;
						break;
					}
				} else {
					// update entry
					if (!$this->VehiclePoiList->save($data)) {
						$flag = false;
						break;
					}
				}
			} else {
				// Do nothing
			}
		}
		return $flag;
	}

}
?>